<template>
    <div class="article-list-edit">
        <div class="article-list-edit-card">
            <Row :gutter="25">
                <Col span="10">
                    <Form ref="formArticleData" :model="formArticleData" :rules="ruleArticleData" :label-width="80">
                        <!--<FormItem label="是否显示">-->
                            <!--<i-switch v-model="formArticleData.switch" size="large">-->
                                <!--<span slot="open">显示</span>-->
                                <!--<span slot="close">隐藏</span>-->
                            <!--</i-switch>-->
                        <!--</FormItem>-->
                        <FormItem label="文章标题" prop="title">
                            <Input v-model="formArticleData.title" placeholder="请输入文章标题"></Input>
                        </FormItem>
                        <FormItem label="分类" prop="type">
                            <Select :disabled="!!($route.query.isEdit)" v-model="formArticleData.type" placeholder="请选择分类">
                                <Option value="1">新闻</Option>
                                <Option value="2">公告</Option>
                                <Option value="3">帮助中心</Option>
                                <!--<Option value="4">美容项目</Option>-->
                            </Select>
                        </FormItem>
                        <FormItem label="价格" prop="title" v-if="this.$route.query.type==4">
                            <Input v-model="formArticleData.money" placeholder="请输入商品价格"></Input>
                        </FormItem>
                        <!--<FormItem label="关键字" prop="font">-->
                            <!--<Input v-model="formArticleData.font" placeholder="请输入关键字"></Input>-->
                        <!--</FormItem>-->
                        <!--<FormItem label="排序号"  prop="num">-->
                            <!--<Input number v-model="formArticleData.num" placeholder="请输入排序号"></Input>-->
                        <!--</FormItem>-->
                    </Form>
                    <template  v-if="formArticleData.type === '1'">
                        <a style="display: block;text-align: left;font-weight: 600;font-size: 17px">标题图片</a>
                        <div style="height: 80px;width: 100px;margin: 0 auto;float: left">
                            <Upload accept="image/png, image/jpeg, image/gif, image/jpg" type="drag" action="?" :before-upload="handleBeforeUploadOne">
                                <div style="height: 80px;line-height: 80px">
                                    <a v-if="bioaImg==``" href="#">上传标题图片</a>
                                    <img v-else style="display: block;width: 100%;height: 100%;" :src="bioaImg"/>
                                </div>
                            </Upload>
                        </div>
                    </template>
                </Col>
                <Col span="14" v-if="formArticleData.type === '1'">
                    <Row :gutter="10">
                        <Col span="12">
                            <Upload accept="image/png, image/jpeg, image/gif, image/jpg" type="drag" action="?" :before-upload="handleBeforeUpload">
                                <div class="upImg">
                                    <a><Icon type="ios-cloud-upload" size="52"></Icon></a>
                                    <p>点击或将图片拖拽到这里上传</p>
                                </div>
                            </Upload>
                        </Col>
                        <!--<Col span="12" class="articleImgChange">-->
                            <!--<img v-if="imgSrc!=''" :src="imgSrc"/>-->
                        <!--</Col>-->
                    </Row>
                </Col>
            </Row>
            <textarea class='tinymce-textarea' id="tinymceEditer"></textarea>
            <div class="subCon">
                <Button type="primary" @click="handleSubmit">提交</Button>
                <Button @click="handleReset">重置</Button>
            </div>
        </div>
    </div>
</template>
<script>
    import tinymce from 'tinymce';
    export default {
        name:"article-add",
        data(){
            const validateNum = (rule, value, callback) => {
                if (value==="") {
                    return callback(new Error('排序号不能为空'));
                }
                // 模拟异步验证效果
                setTimeout(() => {
                    if (!Number.isInteger(value)) {
                        callback(new Error('请输入数字值'));
                    } else {
                        callback();
                    }
                }, 1000);
            };
            return{
                typeList:[],//
                formArticleData:{
                    title:"",
                    type:"",
                    money:'',
                    switch:true,//默认显示
                    // font:"",
                    // num:"",
                },
                ruleArticleData:{
                    title: [
                        { required: true, message: '文章标题不能为空', trigger: 'blur' }
                    ],
                    type: [
                        { required: true, message: '请选择分类', trigger: 'change' }
                    ],
                    // font: [
                    //     { required: true, message: '请输入关键字', trigger: 'blur' }
                    // ],
                    num: [
                        { required: true, validator: validateNum, trigger: 'blur' }
                    ]
                },
                content:"",
                imgSrc:"",//
                isBase64:false,
                imgUrl:'',
                bioaImg:"",
            }
        },
        mounted(){
            if(this.$route.query.isEdit){
                this.getEditCon()
            }else{
                this.init();
            }
            // this.getArticleType()
        },
        methods:{
            // getArticleType(){
            //     this.getJsonData("Articletype/getArticleType",{})
            //         .then((res)=>{
            //             this.typeList=res.data
            //         })
            // },
            //获取需要修改的信息
            getEditCon(){
                this.getJsonData(`Art/index/`,{id:this.$route.query.id})
                    .then((res)=>{
                        this.formArticleData.title = res.arts[0].title;
                        this.formArticleData.type = res.arts[0].type;
                        this.formArticleData.money = res.arts[0].price;
                        this.bioaImg = res.arts[0].pic
                        this.content = res.arts[0].content;
                        this.init();
                        tinymce.get('tinymceEditer').setContent(vm.content)

                    });
                // this.getJsonData("Articles/queryone",{articleId:this.$route.query.id})
                //     .then((res)=>{
                //         this.formArticleData.title=res.data.articletitle
                //         // this.formArticleData.switch=res.data.isshow==1?true:false
                //         // this.formArticleData.font=res.data.articlekey
                //         this.content=res.data.articlecontent
                //         this.formArticleData.type=res.data.catid
                //         // this.formArticleData.num=parseFloat(res.data.articlesort)
                //         this.imgSrc=res.data.articleimg
                //         this.init();
                //     })
            },
            //提交
            handleSubmit () {
                this.$refs.formArticleData.validate((valid) => {
                    if (valid) {
                        // if(this.imgSrc==""){
                        //     this.$Message.warning("请选择图片")
                        // }else{
                            if(this.$route.query.isEdit){
                                if(this.isBase64){
                                    this.$Loading.start();
                                    // this.upBaseImg("User/uploadPic",{image:this.imgSrc})
                                    //     .then((res) =>{
                                            // tinymce.get('tinymceEditer').setContent(`<img src='${res.url}'/>`)
                                            // this.imgSrc = res.url
                                        // })
                                    this.editArticle()
                                }else{
                                    this.$Loading.start();
                                    this.editArticle()
                                }
                            }else{
                                //新增方法
                                this.$Loading.start();
                                this.addArticle(this.imgSrc)
                                // this.upBaseImg("User/uploadPic",{image:this.imgSrc})
                                //     .then((res) =>{
                                //         this.addArticle(res.url)
                                //     })
                            }
                        }
                })
            },
            editArticle(url){
                this.getJsonData("Art/addArt",{
                    id:this.$route.query.id,
                    title:this.formArticleData.title,
                    // isShow:this.formArticleData.switch?1:-1,
                    content:tinymce.get('tinymceEditer').getBody().innerHTML,
                    type:this.formArticleData.type,
                    // type:this.formArticleData.font,
                    // content:this.formArticleData.num,
                    // articleImg:this.isBase64?url:this.imgSrc,
                    pic:this.bioaImg,
                    price:this.formArticleData.money,
                })
                    .then((res)=>{
                        this.$Message.success("修改成功")
                        this.$router.back()
                    })
            },
            addArticle(url){
                this.getJsonData("Art/addArt",{
                    title:this.formArticleData.title,
                    // isShow:this.formArticleData.switch?1:-1,
                    content:tinymce.get('tinymceEditer').getBody().innerHTML,
                    type:this.formArticleData.type,
                    // articleKey:this.formArticleData.font,
                    // articleSort:this.formArticleData.num,
                    // catId:this.formArticleData.type,
                    // image:url,
                    pic:this.bioaImg,
                    price:this.formArticleData.money,
                    })
                    .then((res)=>{
                        this.$Message.success("新增成功")
                        this.$router.back()
                    })
            },
            //重置
            handleReset () {
                this.$refs.formArticleData.resetFields();
            },
            //初始化方法
            init () {
                this.$nextTick(() => {
                    let vm = this;
                    let height = document.body.offsetHeight - 600;
                    tinymce.init({
                        selector: '#tinymceEditer',
                        branding: false,
                        elementpath: false,
                        height: height,
                        language: 'zh_CN.GB2312',
                        menubar: 'edit insert view format table tools',
                        plugins: [
                            'advlist autolink lists link image charmap print preview hr anchor pagebreak imagetools',
                            'searchreplace visualblocks visualchars code fullpage',
                            'insertdatetime media nonbreaking save table contextmenu directionality',
                            'emoticons paste textcolor colorpicker textpattern imagetools codesample'
                        ],
                        toolbar1: ' newnote print preview | undo redo | insert | styleselect | forecolor backcolor bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image emoticons media codesample',
                        autosave_interval: '20s',
                        image_advtab: true,
                        table_default_styles: {
                            width: '100%',
                            borderCollapse: 'collapse'
                        },
                        setup: function (editor) {
                            editor.on('init', function (e) {
                                vm.spinShow = false;
                                tinymce.get('tinymceEditer').setContent(vm.content);//赋值内容
                            });
                            editor.on('keydown', function (e) {
                                /*localStorage.editorContent = tinymce.get('tinymceEditer').getContent();*/
                            });
                        }
                    });
                });
            },
            handleBeforeUploadOne(file){
                if((Math.round(file.size/1024*100)/100)<2000){
                    this.caijianImgOne(file)
                }else{
                    this.$Notice.error({
                        title: '文件过大',
                        desc: '文件 '+file.name +'/'+(Math.round(file.size/1024*100)/100)+'KB'+'，请上传 2M 以内的图片。',
                        duration:4.5
                    });
                }
                //禁止默认上传
                return false
            },
            handleBeforeUpload(file){
                if((Math.round(file.size/1024*100)/100)<2000){
                    this.caijianImg(file)
                }else{
                    this.$Notice.error({
                        title: '文件过大',
                        desc: '文件 '+file.name +'/'+(Math.round(file.size/1024*100)/100)+'KB'+'，请上传 2M 以内的图片。',
                        duration:4.5
                    });
                }
                //禁止默认上传
                return false
            },
            caijianImgOne(file){
                let reader = new FileReader();
                reader.onload = () => {
                    this.upImgOne(reader.result)
                    // this.imgSrc=reader.result
                    this.isBase64=true
                    reader.onload = null;
                };
                reader.readAsDataURL(file);
            },
            caijianImg(file){
                let reader = new FileReader();
                reader.onload = () => {
                    this.upImg(reader.result)
                    // this.imgSrc=reader.result
                    this.isBase64=true
                    reader.onload = null;
                };
                reader.readAsDataURL(file);
            },
            upImg(image){
                this.upBaseImg("User/uploadPic",{image})
                    .then((res) =>{
                        this.imgSrc= this.imgHttpUrl + res.url
                        tinymce.get('tinymceEditer').setContent(tinymce.get('tinymceEditer').getBody().innerHTML+`<img src='${res.url}'/>`)
                    })
            },
            upImgOne(image){
                this.upBaseImg("User/uploadPic",{image})
                    .then((res) =>{
                        this.bioaImg= res.url
                    })
            },
        },
        //销毁初始化
        destroyed () {
            tinymce.get('tinymceEditer').destroy();
        }
    }
</script>
<style lang="less">
    @import "./article-add";
</style>
